package com.smalluz.ad.modules.common.config;

import java.io.Serializable;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.smalluz.ad.modules.common.util.DateUtil;
import com.smalluz.ad.modules.common.util.MediaSDKUtil;
import com.smalluz.ad.modules.ks.result.KsAccessTokenResult;
import com.smalluz.ad.modules.oe.result.AccessTokenResult;

import lombok.Data;

@Data
public class MediaDefaultConfigImpl implements MediaConfigStorage, Serializable {
    protected volatile String appId;

    //广告主ID
    protected volatile String advertiserId;

    //用户ID
    protected volatile String userId;
    
    protected volatile String secret;

    protected volatile String authCode;

    //平台编号
    protected volatile String platformCode;

    //账户编号
    protected volatile String accountNumber;

    protected volatile String grantType = "auth_code";

    protected volatile Lock accessTokenLock = new ReentrantLock();
    /**
     * token值
     **/
    protected volatile String accessToken;
    
    protected volatile String refreshAccessToken;
    
    //过期时间 单位秒
    protected volatile Integer expiresTime;
    
    //刷新过期时间 单位秒
    protected volatile Integer refreshExpiresTime;

    protected volatile Date LastOperationTime;

    private static final long serialVersionUID = 7035764349178191574L;
    
    @Override
    public boolean isAccessTokenValid() {
        return MediaSDKUtil.isAccessTokenValid( this.expiresTime,this.LastOperationTime);
    }
    
    @Override
    public boolean isRefreshAccessTokenValid() {
        return MediaSDKUtil.isAccessTokenValid( this.refreshExpiresTime,this.LastOperationTime);
    }
    
    @Override
    public void updateAccessToken(AccessTokenResult accessToken) {
        this.updateAccessToken(accessToken.getData().getAccessToken(),
                accessToken.getData().getRefreshToken(),
                DateUtil.date(),
                accessToken.getData().getExpiresIn(),
                accessToken.getData().getRefreshTokenExpiresIn());
    }

    @Override
    public void updateAccessToken(String accessToken,String refreshAccessToken, Date LastOperationTime, int expiresInSeconds,int refreshExpiresTime) {
        this.accessToken = accessToken;
        this.refreshAccessToken = refreshAccessToken;
        this.expiresTime = expiresInSeconds;
        this.refreshExpiresTime = refreshExpiresTime;
        this.LastOperationTime = LastOperationTime;
    }

    @Override
    public void updateAccessKsToken(KsAccessTokenResult accessToken) {
        this.updateAccessToken(accessToken.getData().getAccessToken(),
                accessToken.getData().getRefreshToken(),
                DateUtil.date(),
                accessToken.getData().getAccessTokenExpiresIn(),
                accessToken.getData().getRefreshTokenExpiresIn());
    }
  

    @Override
    public synchronized void expireAccessToken() {
        this.expiresTime = -10;
    }

   

}
